Ext.ns('AIR2.Drawer');
/***************
 * AIR2 Drawer Toolbar Component
 *
 * An Ext.Toolbar for use as the top toolbar of an AIR2 drawer.
 *
 * @class AIR2.Drawer.Toolbar
 * @extends Ext.Toolbar
 * @cfg {Function} startNewFn
 *   Function that toolbar should call to create a new Bin.
 * @cfg {Function} deleteFn
 *   Function that toolbar should call to delete a Bin.
 *
 */
AIR2.Drawer.Toolbar = function(config) {
    this.startNewFn = config.startNewFn;
    this.deleteFn = config.deleteFn;

    // create the "filter" menu
    this.filterMenu = new Ext.menu.Menu({
        cls: 'air2-drawer-filters',
        showSeparator: false,
        defaults: {
            clickHideDelay: 750,
            checkHandler: this.filterClicked.createDelegate(this)
        }
    });

    // create the "sort by" menu
    this.sortMenu = new Ext.menu.Menu({
        cls: 'air2-drawer-filters',
        showSeparator: false,
        defaults: {clickHideDelay: 750},
        listeners: {
            itemclick: this.sortClicked.createDelegate(this)
        }
    });

    // create the "random output" menu
    var randMenu = new Ext.menu.Menu({
        items: {
            xtype: 'form',
            plain: true,
            labelWidth: 50,
            border: false,
            buttonAlign: 'center',
            title: '<b class="menu-title">Random Output</b>',
            padding: '4px 0 0 0',
            items: [{
                id: 'bin-random-number',
                xtype: 'spinnerfield',
                fieldLabel: 'Number',
                minValue: 1,
                value: 2,
                width: 54,
                scope: this,
                enableKeyEvents: true,
                listeners: {
                    validspin: function(fld, newVal) {
                        var size = Ext.getCmp('bin-random-size').getValue();
                        return randMenu.isRandomValid(newVal, size);
                    },
                    keydown: function(fld, ev) {
                        fld.preDownVal = fld.getValue();
                    },
                    keyup: function(fld, ev) {
                        var newVal = fld.getValue();
                        var size = Ext.getCmp('bin-random-size').getValue();
                        if (!randMenu.isRandomValid(newVal, size)) {
                            fld.setValue(fld.preDownVal);
                        }
                    }
                }
            },{
                id: 'bin-random-size',
                xtype: 'numberfield',
                fieldLabel: 'Size',
                emptyText: 'auto',
                width: 54,
                allowDecimals: false,
                minValue: 1,
                maxValue: 800,
                enableKeyEvents: true,
                listeners: {
                    keyup: function(fld, ev) {
                        var newVal = fld.getValue();
                        var number = Ext.getCmp('bin-random-number').getValue();
                        if (!randMenu.isRandomValid(number, newVal)) {
                            fld.setValue(fld.lastValid);
                        }
                        else if (Ext.isNumber(newVal) && (newVal < 1 || newVal > 800)) {
                            fld.setValue(fld.lastValid);
                        }
                        else {
                            fld.lastValid = newVal;
                        }
                    }
                }
            },{
                xtype: 'container',
                items: [{
                    xtype: 'air2button',
                    text: 'Create',
                    air2type: 'BLUE',
                    handler: function(b) {
                        var f = this.randMenu.get(0);
                        if (f.getForm().isValid()) {
                            var num = f.get(0).getValue();
                            var size = f.get(1).getValue();
                            this.randomClicked(num, size);
                            f.ownerCt.hide(true); //hide menu
                        }
                    }.createDelegate(this)
                }]
            }]
        },
        listeners: {
            show: function() {
                var r = this.view.getSelectedRecords()[0];
                var total = r.get('batch_count');
                randMenu.batchCount = total;
            },
            scope: this
        },
        isRandomValid: function(number, size) {
            this.batchCount;
            if (number && size) {
                return (number * size <= this.batchCount);
            }
            else if (number) {
                return (number <= this.batchCount);
            }
            else {
                return (size <= this.batchCount);
            }
        }
    });
    this.randMenu = randMenu;

    config.defaults = {
        cls: 'air2-drawer-btn',
        scope: this
    };
    config.items = ['-', {
        xtype: 'air2textfilter',
        listeners: {
            filterchange: function(field, value) {
                if (this.view.applyFilter) {
                    this.view.applyFilter(value);
                }
                else {
                    this.view.ownerCt.applyFilter(value);
                }
            },
            scope: this
        },
        setView: function(vw, dview) {
            this.emptyText = (vw == 'si') ? 'Filter Bin' : 'Search Title';
            this.reset();

            // set any search strings
            var p = dview.store.baseParams;
            if (p.q && p.q.length > 0) this.setValue(p.q);
        }
    },'-',{
        iconCls: 'air2-icon-merge',
        tooltip: 'Merge Bins',
        handler: this.mergeClicked,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        },
        setBinStatus: function(count, sameType, mayManage) {
            this.setDisabled(!sameType || count < 2);
        }
    },{
        iconCls: 'air2-icon-duplicate',
        tooltip: 'Duplicate Bin',
        handler: this.mergeClicked,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        },
        setBinStatus: function(count, sameType, mayManage) {
            this.setDisabled(count != 1);
        }
    },{
        iconCls: 'air2-icon-delete',
        tooltip: 'Delete Bin',
        handler: this.deleteClicked,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        },
        setBinStatus: function(count, sameType, mayManage) {
            this.setDisabled(!mayManage || count != 1);
        }
    },{
        iconCls: 'air2-icon-random',
        tooltip: 'Random Output',
        menuAlign: 'tr-br?',
        menu: this.randMenu,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        },
        setBinStatus: function(count, sameType, mayManage, batchCount) {
            this.setDisabled(count != 1 || batchCount < 2);
        }
    },{
        xtype: 'box',
        setTotal: function(s) {
            this.update(s.getTotalCount()+' Total');
        },
        setView: function(vw, dview) {
            // update the total-listener
            this.setVisible(vw == 'si');
            if (vw == 'si') {
                this.cachestore = dview.store;
                this.setTotal(dview.store);
                dview.store.on('load', this.setTotal, this);
            }
            else if (this.cachestore) {
                this.cachestore.un('load', this.setTotal, this);
            }
        }
    },'->', {
        text: 'Filters',
        menuAlign: 'tr-br?',
        menu: this.filterMenu,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        }
    },{
        text: 'Sort',
        menuAlign: 'tr-br?',
        menu: this.sortMenu,
        setView: function(vw) {
            this.setVisible(vw == 'lg');
        }
    },{
        xtype: 'air2button',
        air2type: 'DRAWER',
        iconCls: 'air2-icon-remove-sel',
        text: 'Remove Selected',
        handler: this.removeClicked,
        setView: function(vw) {
            this.setVisible(vw == 'si');
        },
        setBinStatus: function(count, sameType, mayManage) {
            this.setDisabled(!mayManage || count < 1);
        }
    },{
        xtype: 'air2button',
        air2type: 'BLUE',
        iconCls: 'air2-icon-upload',
        text: 'Export CSV',
        handler: this.exportClicked,
        setView: function(vw) {
            this.setVisible(vw == 'si');
        }
    }];

    // call parent constructor
    AIR2.Drawer.Toolbar.superclass.constructor.call(this, config);

}
Ext.extend(AIR2.Drawer.Toolbar, Ext.Toolbar, {
    cls: 'air2-bin-tbar',
    setView: function(vwStr, vwObj) {
        //un-listen to the previous view
        if (this.view) this.view.un('selectionchange', this.selChange, this);

        this.view = (vwStr == 'si') ? vwObj.livedv : vwObj;
        this.viewstr = vwStr;
        this.view.on('selectionchange', this.selChange, this);

        this.changeToolbar(vwStr, this.view);
        this.selChange(this.view, []);
        this.changeFilterMenu(vwStr);
        this.changeSortMenu(vwStr);
    },
    selChange: function(dv, sel) {
        var count = sel.length;
        var same = true;
        var recs = dv.getSelectedRecords();
        for (var i=0; i<recs.length-1; i++) {
            var d1 = recs[i].data;
            var d2 = recs[i+1].data;
            var t1 = (d1.batch_type) ? d1.batch_type : d1.bitem_type;
            var t2 = (d2.batch_type) ? d2.batch_type : d2.bitem_type;
            if (t1 != t2) {
                same = false;
                break;
            }
        }
        var mayManage = (AIR2.USERINFO.type == 'S');
        if (recs.length == 1 && recs[0].data.batch_owner) {
            mayManage = true;
        }
        if (dv.ownerCt && dv.ownerCt.binRecord && dv.ownerCt.binRecord.data.batch_owner) {
            mayManage = true;
        }
        var batchCount = null;
        if (recs.length == 1) {
            batchCount = recs[0].data.batch_count;
        }

        // update enable/disable of items
        this.items.each(function(item) {
            if (item.setBinStatus) {
                item.setBinStatus(count, same, mayManage, batchCount);
            }
        });
    },
    changeToolbar: function(newType, dview) {
        this.items.each(function(item) {
            if (item.setView) {
                item.setView(newType, dview);
            }
        });
    },
    changeFilterMenu: function(newType) {
        this.filterMenu.removeAll(true);
        if (newType == 'lg') {
            this.filterMenu.add(AIR2.Drawer.Config.FILTERS.lg);
        }

        // determine the filters from the store
        var p = this.view.store.baseParams;
        this.filterMenu.items.each(function(it) {
            if (it.param) {
                it.setChecked((p[it.param] == 1), true);
            }
        });
    },
    changeSortMenu: function(newType) {
        this.sortMenu.removeAll(true);

        if (newType == 'lg')
            this.sortMenu.add(AIR2.Drawer.Config.SORTFIELDS.lg);

        // determine the sorting order from the store
        var s = this.view.store.getSortState();
        this.sortMenu.items.each(function(it) {
            if (it.fld == s.field) {
                var d = s.direction;
                if ((d == 'ASC' && !it.flip) || (d == 'DESC' && it.flip)) {
                    it.setIconClass('air2-icon-sort-asc');
                    it.state = 'ASC';
                } else {
                    it.setIconClass('air2-icon-sort-desc');
                    it.state = 'DESC';
                }
            }
        });
    },
    filterClicked: function(item, checked) {
        if (item.param) {
            this.view.store.setBaseParam(item.param, (checked) ? 1 : 0);
        }
        else if (item.typeCode) {
            var t = '', items = item.parentMenu.items;
            item.parentMenu.items.each(function(it) {
                if (it.checked) t += it.typeCode;
            });
            this.view.store.setBaseParam('type', t);
        }
        this.view.reloadDataView();
    },
    sortClicked: function(item, e) {
        this.sortMenu.items.each(function(it) {
            if (it == item) {
                if (it.state == 'DESC') {
                    it.state = 'ASC';
                    it.setIconClass('air2-icon-sort-asc');
                }
                else {
                    it.state = 'DESC';
                    it.setIconClass('air2-icon-sort-desc');
                }
                this.view.store.sortInfo = {field: it.fld, direction: it.state};

                //allow flipping the sort direction
                if (it.flip && this.view.store.sortInfo.direction == 'ASC')
                    this.view.store.sortInfo.direction = 'DESC';
                else if (it.flip && this.view.store.sortInfo.direction == 'DESC')
                    this.view.store.sortInfo.direction = 'ASC';
                this.view.reloadDataView();
            }
            else {
                it.state = null;
                it.setIconClass('');
            }
        }, this);
    },
    mergeClicked: function() {
        if (this.view.getSelectionCount() > 0) {
            var sel = this.view.getSelectedRecords();

            // double-check that all batch types match
            var type = sel[0].get('batch_type');
            for (var i=0; i<sel.length; i++) {
                type = (sel[i].get('batch_type') == type) ? type : null;
            }
            if (type) {
                this.startNewFn(type, null, sel);
            }
        }
    },
    deleteClicked: function() {
        var sel = this.view.getSelectedRecords();
        this.deleteFn(sel);
    },
    randomClicked: function(num, size) {
        var v = this.view;
        if (v.getSelectionCount() == 1) {
            var l = this.view.el, r = v.getSelectedRecords()[0];
            l.mask("Generating Random Bins");
            AIR2.Drawer.API.random(r, num, size, function(data, success) {
                l.unmask();
                if (success) v.reloadDataView();
            });
        }
    },
    removeClicked: function() {
        var v = this.view;
        if (v.getSelectionCount() > 0) {
            var owner = v.ownerCt;
            var l = owner.el, r = owner.binRecord, sel = v.getSelectedRecords();
            l.mask('Removing Items');
            AIR2.Drawer.API.removeItems(r, sel, function(data, success) {
                if (success) {
                    v.store.on('load', function() {
                        l.unmask();
                    }, this, {single: true});
                    v.reloadDataView(true);
                }
                else {
                    l.unmask();
                }
            });
        }
    },
    exportClicked: function() {
        var r = this.view.ownerCt.binRecord;
        var loc = AIR2.HOMEURL+'/batch/'+r.get('batch_uuid')+'/contents.csv';
        location.href = loc;
    }
});
Ext.reg('air2drawertbar', AIR2.Drawer.Toolbar);